<template>
	<view class="mpBuyTickets">
		<!-- <img class="gifImg" :src="imgUrl+'upload/img/ws_static/mp_pic/bdcBg.gif'" alt="gif图片" /> -->
		<!-- <img class="gifImg" src="@/static/traffic/bdcBg.gif" alt="gif图片" /> -->
		<image class="gifImg" :src="imgUrl + 'upload/img/ws_static/static/traffic/bdcBg.gif'" mode="widthFix"></image>
		<view class="tab" v-if="!isAll">
			<view :class="['tabItem', { active: tab === 'buy' }]" @click="changeTab('buy')">
				购票
			</view>
			<view :class="['tabItem', { active: tab === 'check' }]" @click="changeTab('check')">
				核票
			</view>
		</view>
		<view v-if="!isAll && tab === 'buy'" class="buyBox">
			<view class="tabBox">
				<view class="roadName">
					<view class="name">
						{{ routeInfo.name }}
					</view>
					<view class="viewMap" @click="viewMap()"> 查看交通图 </view>
				</view>
				<view class="routeSummary" v-if="routeInfo && routeInfo.productId == 103">
					3元-海鲜时长，5元-初心广场，10全程
				</view>
				<view class="ticketSection">
					<view class="ticketTitle">
						<view>
							票价
						</view>
						<!-- <text class="ticketTime" v-if="routeInfo.firstBusTime && routeInfo.lastBusTime">
							(首车{{ routeInfo.firstBusTime }} 末车{{
                routeInfo.lastBusTime
              }})</text>
						<text class="ticketTime" v-else>{{
              routeInfo.totalTime || ""
            }}</text> -->
						<view class="ticketTime">
							{{routeInfo.specialNote}}
						</view>
					</view>
					<view class="ticketTypes">
						<view v-for="(item, idx) in priceList" :key="item.price"
							:class="['ticketType', { active: selectedTypeIndex === idx }]" @click="selectType(idx)">
							<!-- {{ item.name }}<br />￥{{ item.price }} -->
							<view class="ticketTypeLeft">
								<view class="ticketName">
									{{ item.name }}
								</view>
								<view class="ticketSpecName">
									{{ item.specName }}
								</view>
							</view>
							<view class="ticketTypeRight">
								￥<text class="ticketPrice">{{ item.price }}</text>
							</view>

							<!-- <uni-icons class="tIcon" type="checkmarkempty"></uni-icons> -->
							<image v-if="selectedTypeIndex === idx" class="tIcon"
								:src="imgUrl + 'upload/img/ws_static/static/traffic/check.png'" mode="widthFix"></image>
						</view>
					</view>
					<view class="quantityBox">
						<text>购买数量</text>
						<view class="quantityBtnList">
							<button class="qtyBtn" @click="changeQty(-1)" :disabled="form.quantity <= 1"
								v-if="locationId === 713041">
								-
							</button>
							<text class="qtyNum">{{ ticketCount }}</text>
							<button class="qtyBtn" @click="changeQty(1)" v-if="locationId === 713041">+</button>
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="refundInstructions" @click="openDesc"> 退票说明> </view> -->
			<!-- 乘客信息 -->
			<view class="passenger-info-card" v-if="locationId !== 713041">
				<view class="info-header">
					<view class="info-title">{{$t('ticket.booking.passengerInfo')}} <text
							class="passenger-count-tip">({{$t('ticket.booking.passengerCountTip')}})</text></view>
					<view class="add-passenger-btn" @click="openPassengerSelector">
						<text class="add-icon">+</text>
						<text class="add-text">{{$t('ticket.booking.addPassenger')}}</text>
					</view>
				</view>

				<!-- 乘客列表 -->
				<view class="passenger-list">
					<view class="passenger-item" v-for="(passenger, index) in passengers" :key="index">
						<view class="passenger-index">{{$t('ticket.booking.passenger', {index: index + 1})}}</view>
						<view class="passenger-details">
							<text class="passenger-name">{{passenger.name}}</text>
							<text class="id-number">- {{passenger.phone}}</text>
							<text class="id-full">{{passenger.idCard}}</text>
						</view>
						<view class="delete-btn" @click="removePassenger(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>

					<!-- 没有乘客时的提示 -->
					<view class="no-passenger" v-if="passengers.length === 0">
						<text class="no-passenger-tip">{{$t('ticket.booking.noPassengerTip')}}</text>
					</view>
				</view>
			</view>

			<!-- 优惠券区域 -->
			<view class="coupon-area mt30">
				<view class="coupon-section">
					<view class="coupon-header">
						<view class="section-title">优惠券</view>
						<view class="coupon-status" v-if="useCoupons.length > 0">
							已选择{{useCoupons.length}}张，已优惠¥{{couponTotalDiscount.toFixed(2)}}
						</view>
						<view class="coupon-status available" v-else-if="hasCoupons">
							有可用优惠券
						</view>
						<view class="coupon-status unavailable" v-else>
							暂无可用优惠券
						</view>
					</view>
					<view class="coupon-selection" @click="navigateToCoupons">
						<view class="select-text">选择优惠券</view>
						<image src="/static/home/right-arrow-black.png" class="arrow-icon"></image>
					</view>
				</view>
			</view>

			<view class="footerBar">
				<view class="agreement" @click="changeCheked">
					<uni-icons class="agreementIcon" v-if="checked" type="circle-filled" color="#1AAC19"
						size="26"></uni-icons>
					<uni-icons class="agreementIcon" v-else type="circle" color="#1AAC19" size="26"></uni-icons>
					<view class="agreementText">
						我已阅读协议
						<text class="blueText" @click.stop="viewAgreement(5773)">《用户协议》</text>、
						<text class="blueText" @click.stop="viewAgreement(5774)">《隐私政策》</text>、
						<text class="blueText" @click.stop="viewAgreement(5775)">《免责声明》</text>
					</view>

				</view>
				<view class="footerBarBox">
					<view class="totalPrice"><text class="name">总价</text> ￥
						<text class="price">{{ totalPrice.toFixed(2) }}</text>
					</view>
					<view class="buyBtn" @click="submitOrder"> 立即购买 </view>
				</view>
			</view>
		</view>

		<view v-else>
			<!-- <view class="noticeBar"> 请提前到达站点等候上车 </view> -->
			<view class="checkTicketBox" v-if="ticketData">
				<view class="ticketCard">
					<view class="ticketHeader">
						<view class="noticeBar"> 请提前到达站点等候上车 </view>
						<view class="ticketHeaderBox">
							<view class="ticketInfo">
								<view class="ticketTitle">
									{{ ticketData.OrdersOnlineInfoViewList[0].ProductName }}
									<text class="ticketStatus">{{
                    typeText(ticketData.Type)
                  }}</text>
								</view>
								<!-- 	<view class="ticketDetail">
									{{order.OrdersOnlineInfoViewList[0].SalePrice}}{{order.OrdersOnlineInfoViewList[0].ProductSpecStr}}
								</view> -->
								<view class="ticketDate">
									<view class="ticketDateBox">
										<!-- <view class="date" :style="{color:color}">
											{{ formattedDate }}
										</view> -->

										<text class="label" v-if="ticketData.VerifyTime">核销时间</text>
										<!-- <digital-clock :color="color"></digital-clock> -->
										<view class="date">
											{{ ticketData.VerifyTime || "" }}
										</view>
									</view>
									<view class="ticketCountCircle">
										<view class="price">{{
                      ticketData.OrdersOnlineInfoViewList[0].SalePrice
                    }}</view>
										元/人
										<view class="countBox">
											{{ ticketData.OrdersOnlineInfoViewList.length }}
											<text class="unit">张</text>
										</view>
									</view>
								</view>
								<view class="idCards"
									v-if="ticketData && ticketData.PersonsCodes && ticketData.PersonsCodes.length > 0">
									身份证后四位：<text class="num">{{ ticketData.PersonsCodes }}</text>
								</view>
							</view>
						</view>
					</view>
					<!-- 	<view class="dashedLineWrap">
						<view class="halfCircle left"></view>
						<view class="dashedLine"></view>
						<view class="halfCircle right"></view>
					</view> -->
					<image class="lineImg" :src="imgUrl + 'upload/img/ws_static/static/line.png'" mode="widthFix">
					</image>
					<!-- <img class="lineImg" src="../img/line.png" alt="" /> -->
					<!-- <view class="lineBox">

					</view> -->
					<view class="qrSection" v-if="ticketData.OrdersOnlineInfoViewList.length > 0">
						<view class="qrTips"> 请依次出示车票 </view>
						<view class="qrTypeList"
							v-if="ticketData.ProductSpecStr2 && ticketData.ProductSpecStr2.length>0">
							<view class="qrType" :style="{ color: ticketData.color }"
								v-for="(spec,index) in ticketData.ProductSpecStr2" :key="index">
								{{ spec }}
							</view>
						</view>
						<view class="qrType" :style="{ color: ticketData.color }" v-else>
							{{ ticketData.OrdersOnlineInfoViewList[0].ProductSpecStr }}
						</view>
						<view class="qrImg">
							<view class="canvas-container">
								<view v-if="ticketData.Type == 15" class="noQRCode" @click="openQRCode">
									<image class="qrcodeImg" :src="
                      imgUrl + 'upload/img/ws_static/static/ticket/qrcode.png'
                    " mode="widthFix">
									</image>
									<view class="maskBox">
										<view class="maskText">出示即核销</view>
									</view>
								</view>
								<canvas v-else id="qrcode" canvas-id="qrcode"
									style="width: 170px; height: 170px"></canvas>
							</view>
						</view>
						<view class="numBox">
							<view class="spot" v-if="ticketList.length && ticketList.length > 0">
								<view class="spotItem" v-for="(item, index) in ticketList" :key="index"
									:class="{ active: codeIndex === index }">
								</view>
							</view>
							<view class="changeBtn" v-if="ticketList.length && ticketList.length > 1">
								<image class="leftBtn" :src="
                    imgUrl + 'upload/img/ws_static/static/traffic/leftBtn.png'
                  " mode="widthFix" @click="prevTicket"></image>
								<image class="rightBtn" :src="
                    imgUrl + 'upload/img/ws_static/static/traffic/rightBtn.png'
                  " mode="widthFix" @click="nextTicket"></image>
							</view>
						</view>
					</view>
					<!-- <view class="useBtn" disabled>点击使用</view> -->
				</view>
			</view>
			<view class="noData" v-else> 暂无数据 </view>
			<view class="trafficMap" @click="viewMap">
				<image class="trafficMapBG" :src="imgUrl + 'upload/img/ws_static/static/traffic/map.png'"
					mode="widthFix">
				</image>
				<view class="trafficMapBox">
					<view class="TMTitle"> 查看实景交通图 </view>
					<image class="addressIcon" :src="imgUrl + 'upload/img/ws_static/static/traffic/adress.png'"
						mode="widthFix"></image>
				</view>
			</view>
		</view>
		<u-popup :show="showDesc" @close="closeDesc" mode="bottom" round="10">
			<view class="descBox">
				<view class="title"> 退票说明 </view>
				<view class="content"> xxx </view>
			</view>
		</u-popup>

		<!-- 乘客选择弹窗 -->
		<uni-popup ref="userSelector" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">{{$t('ticket.booking.selectPassenger') || '选择乘客'}}</text>
					<text class="popup-close" @click="$refs.userSelector.close()">×</text>
				</view>
				<view class="popup-body">
					<select-user :selectedGuests="currentSelectedGuests" @select="addPassenger" @clear="clearPassengers"
						@complete="onSelectComplete"></select-user>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getGoodsDetail,
		addEleCouponOrders,
		getBdcRoute,
		getUserOrderList,
		PostUserOrderListToBeVerified,
		getOrderDetails,
	} from "@/api/mall";
	import UQRCode from "uqrcodejs";
	import DigitalClock from "./components/digital-clock/digital-clock.vue";
	import Config from "@/config";
	import {
		forEach,
		formatDate
	} from "@/utils/tools.js";
	import selectUser from '@/components/selectUser/index.vue';
	export default {
		components: {
			DigitalClock,
			selectUser
		},
		data() {
			return {
				tab: "check",
				selectedTypeIndex: 1, // 默认选中5元
				// 表单数据
				form: {
					specId: "", // 规格ID
					price: 0,
					quantity: 1,
				},
				// 线路数据
				routeInfo: null,
				// 区域和线路ID
				locationId: 2,
				routeId: 1,
				products: {},

				// 价格列表
				priceList: [],
				// 加载状态
				loading: true,
				//二维码相关参数
				modal_qr: false,
				url: "暂无数据", // 要生成的二维码值
				intervalId: null,
				color: "#FF6B0D",
				// 线路数据 (从config.js移过来)
				routesData: {
					// 全部景区（默认）
					0: [],
				},
				ticketList: [],
				codeIndex: 0,
				imgUrl: Config.imgUrl,
				checked: false, //协议
				showDesc: false,
				ticketData: null,
				isAll: false,
				productIds: "",

				// 优惠券相关数据
				hasCoupons: false,
				useCoupons: [],
				couponTotalDiscount: 0,

				// 价格动画
				lastTotalPrice: 0,


				// 乘客相关数据
				passengers: [],
				currentSelectedGuests: []
			};
		},

		computed: {
			totalPrice() {
				return this.form.price * this.ticketCount;

				// 减去优惠券折扣
				if (this.couponTotalDiscount > 0) {
					totalPrice -= this.couponTotalDiscount;
					// 确保价格不低于0
					totalPrice = Math.max(0, totalPrice);
				}

				// 四舍五入保留两位小数
				totalPrice = Math.round(totalPrice * 100) / 100;

				return totalPrice;
			},
			formattedDate() {
				const now = new Date();
				const month = now.getMonth() + 1;
				const day = now.getDate();
				return `${month}月${day}日`;
			},
			// 票务数量 - 等于乘客数量，或可手动输入
			ticketCount() {
				if (this.locationId === 713041) {
					return this.form.quantity;
				} else {
					return Math.max(1, this.passengers.length);
				}
			}
		},
		async onLoad(option) {
			// 获取路由参数中的线路ID和区域ID
			const routeId = parseInt(option.id || '1');
			const locationId = parseInt(option.locationId || '2'); // 默认东澳岛
			this.locationId = locationId;
			this.routeId = routeId;
			this.isAll = option.isAll ? true : false;
			console.log("接收到的线路ID:", routeId, "区域ID:", locationId);

			await this.fetchRouteData();
		},
		mounted() {},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		},
		methods: {
			// 跳转到优惠券选择页面
			navigateToCoupons() {
				// 准备传递的参数
				const params = {
					businessId: this.products.BusinessId,
					totalPrice: this.totalPrice,
					productId: this.products.Id,
					selectedCoupons: this.useCoupons || [] // 传递已选择的优惠券
				};

				// 跳转到优惠券页面
				uni.navigateTo({
					url: '/mall_subpages/goods/coupons?params=' + encodeURIComponent(JSON.stringify(params))
				});
			},
			// 从优惠券页面返回时接收数据
			onCouponSelected(coupons) {
				// 记录当前价格作为起始值
				this.lastTotalPrice = this.totalPrice;

				this.useCoupons = coupons || [];

				// 计算优惠券总折扣金额
				this.calculateCouponDiscount();
			},

			// 计算优惠券总折扣金额
			calculateCouponDiscount() {
				if (!this.useCoupons || this.useCoupons.length === 0) {
					this.couponTotalDiscount = 0;
					return;
				}

				let totalDiscount = 0;
				const originalPrice = parseFloat(this.form.price * this.ticketCount);

				this.useCoupons.forEach(coupon => {
					if (coupon.CouponTemple && coupon.CouponTemple.FullReduceAmount) {
						totalDiscount += parseFloat(coupon.CouponTemple.FullReduceAmount);
					}
				});

				// 确保折扣不超过总价
				this.couponTotalDiscount = Math.min(totalDiscount, originalPrice);
			},

			// 构建优惠券参数
			buildCouponParams() {
				if (!this.useCoupons || this.useCoupons.length === 0) {
					return [];
				}

				return this.useCoupons.map(coupon => ({
					CouponCode: coupon.CouponCode,
					BusinessId: coupon.BusinessIds ? this.products.BusinessId : 0
				}));
			},


			// 乘客相关方法
			// 打开乘客选择弹窗
			openPassengerSelector() {
				// 更新当前已选乘客列表，用于传递给选择器组件
				this.currentSelectedGuests = [...this.passengers];

				// 打开乘客选择弹窗
				this.$refs.userSelector.open();
			},

			// 添加乘客（由选择器组件触发）
			addPassenger(passenger) {
				this.passengers.push(passenger);
			},

			// 删除乘客
			removePassenger(index) {
				this.passengers.splice(index, 1);
			},

			// 清空乘客列表（由选择器组件触发）
			clearPassengers() {
				this.passengers = [];
			},

			// 完成乘客选择（由选择器组件触发）
			onSelectComplete() {
				// 关闭选择器弹窗
				this.$refs.userSelector.close();
			},
			typeText(type) {
				if (type == 15) {
					return "待核销";
				} else {
					return "已核销";
				}
			},
			giveColor(type) {
				if (type == "分段票") {
					return "#9B5734";
				} else if (type == "单程票") {
					return "#00ACF4";
				} else if (type == "双程票") {
					return "#4285F4";
				} else if (type == "通票") {
					return "#30A8B5";
				} else if (type == "包票") {
					return "#FFAC15";
				} else if (type == "双日票") {
					return "#FF6B0D";
				} else if (type == "三日票") {
					return "#FA452D";
				} else {
					return "#333333";
				}
			},
			closeDesc() {
				this.showDesc = false;
			},
			openDesc() {
				this.showDesc = true;
				console.log("显示退票说明");
			},
			viewAgreement(id) {
				console.log("查看协议");
				uni.navigateTo({
					url: `/ticket_subpages/index/article?id=${id}`
				});
			},
			changeCheked() {
				this.checked = !this.checked;
			},
			async getOrderList() {
				try {
					const date = formatDate(new Date());
					let productId = this.isAll ? this.productIds : this.routeInfo.productId;
					let param = {
						Index: 1,
						Size: 999,
						ProductId: productId,
						TypeArr: "6,15,20", //待使用
						EndUseTimestart: date,
					}
					const res = await getUserOrderList(param);
					this.ticketIndex = 0;
					this.ticketData = null;
					if (res.Code == 200) {
						// 获取今天的日期（年月日）
						// const today = new Date();
						// const todayStr = today.toISOString().split('T')[0];

						// 过滤出今天的票
						// this.ticketList = res.Data.filter(ticket => {
						// 	const ticketDate = new Date(ticket.AddTime);
						// 	const ticketDateStr = ticketDate.toISOString().split('T')[0];
						// 	return ticketDateStr === todayStr;
						// });

						this.ticketList = res.Data; //测试数据

						if (this.ticketList.length > 0) {
							this.ticketList.map((v) => {
								v.color = this.giveColor(
									v.OrdersOnlineInfoViewList[0].ProductSpecStr
								);
								const specStr = v.OrdersOnlineInfoViewList[0].ProductSpecStr;
								const leftIdx = specStr.indexOf('（');
								if (leftIdx === -1) {
									v.ProductSpecStr2 = [];
								} else {
									const before = specStr.substring(0, leftIdx);
									const after = specStr.substring(leftIdx); // 包含 '（' 及后续内容
									v.ProductSpecStr2 = [before, after];
								}
							});
							this.ticketData = this.ticketList[0];
							await this.getOrderData();
							this.$nextTick(() => {
								this.showQrcode(); //一加载生成二维码
								this.tab = "check";
							});
						} else {
							this.tab = "buy";
						}
					} else {
						this.ticketList = [];
						this.tab = "buy";
					}
					console.log("ticketData =>", this.ticketData);
					console.log("ticketList =>", this.ticketList);
				} catch (e) {
					console.error("获取订单异常:", e);
					uni.showToast({
						title: "网络异常，请重试",
						icon: "none",
					});
				}
			},
			async getOrderData() {
				const {
					Data
				} = await getOrderDetails({
					OrdersOnLineId: this.ticketData.OrdersOnLineId,
				});
				console.log("Data =>", Data);
				console.log("ProductOrdersPersonsList =>", Data?.ProductOrdersPersonsList);

				if (Data && Data.ProductOrdersPersonsList) {
					const personsCodes = Data.ProductOrdersPersonsList.map(
						(person) => {
							// 获取身份证号后四位
							const idCard = person.IDCard || "";
							console.log("处理身份证号:", idCard, "后四位:", idCard.slice(-4));
							return idCard.slice(-4); // 取后四位
						}
					).join(","); // 用逗号拼接

					// console.log("生成的PersonsCodes:", personsCodes);

					// 直接修改this.ticketData对象，确保响应式更新
					this.$set(this.ticketData, 'PersonsCodes', personsCodes);

					// console.log("设置后的ticketData.PersonsCodes:", this.ticketData.PersonsCodes);
				} else {
					// console.log("没有找到ProductOrdersPersonsList数据");
				}
			},
			// 从接口获取线路数据
			async fetchRouteData() {
				try {
					const res = await getBdcRoute();
					if (res && res.Data) {
						// 解析返回的JSON字符串为对象
						let data = JSON.parse(res.Data);
						console.log("路线信息 data =>", data);
						// 确保存在0:[]项
						if (!data[0]) {
							data[0] = [];
						}

						if (Object.keys(data).length > 0) {
							let ids = "";
							for (let key in data) {
								if (data[key].length > 0) {
									data[key].map((v) => {
										if (ids) {
											ids += "," + v.productId;
										} else {
											ids = v.productId;
										}
									});
								}
							}
							this.productIds = ids;
							console.log("全部 productIds =>", ids);
						}
						this.routesData = data;
						// 加载线路数据
						if (this.isAll) {
							await this.getOrderList();
						} else {
							await this.getRouteDetail(data);
						}
					} else {
						console.error("获取线路数据失败:", res);
						uni.showToast({
							title: "获取线路数据失败",
							icon: "none",
						});
					}
				} catch (error) {
					console.error("获取线路数据异常:", error);
					uni.showToast({
						title: "网络异常，请重试",
						icon: "none",
					});
				}
			},
			async openQRCode() {
				try {
					let arr = [];
					this.ticketData.OrdersOnlineInfoViewList.forEach((con) => {
						let obj = {
							ProductOrdersCouponInfoCode: con.Code,
							OrdersCouponId: con.OrdersCouponId,
							UsersId: "",
							OrdersOnLineId: con.OrdersOnLineId,
							OrdersOnLineType: con.OrdersOnLineType,
						};
						arr.push(obj);
					});
					const {
						Data
					} = await PostUserOrderListToBeVerified(arr);
					console.log(Data);
					this.$api.msg("核销成功");
					this.getOrderList();
					// this.loadData()
				} catch (e) {
					console.log(e);
					//TODO handle the exception
				}
			},

			// 展示二维码
			showQrcode() {
				if (!this.ticketData.Type == 15) {
					return;
				}
				// this.modal_qr = true;
				setTimeout(() => {
					this.ticketList.forEach((ticket, index) => {
						this.loadQRCode(this.ticketData.OrdersOnlineInfoViewList[0].Code);
					});
				}, 100);
			},

			loadQRCode(QrCode) {
				const code = QrCode;
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = code;
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 170;
				// 设置二维码颜色
				qr.foregroundColor = this.ticketData.color || "#333333";
				// 调用制作二维码方法
				qr.make();
				// 获取canvas上下文
				var canvasContext = uni.createCanvasContext("qrcode", this);
				// 设置uQRCode实例的canvas上下文
				qr.canvasContext = canvasContext;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr.drawCanvas();
			},

			//传入组件的方法
			hideQrcode() {
				this.modal_qr = false;
			},
			changeTab(tab) {
				if (tab === "check") {
					if (this.ticketList.length > 0) {
						this.$nextTick(() => {
							this.getOrderList();
						});
					} else {
						uni.showToast({
							title: '暂无车票，请先购买车票',
							icon: "none",
						})
						return;
					}
				}
				this.tab = tab;
			},
			// 获取线路详情
			getRouteDetail(routeData) {
				this.loading = true;

				try {
					let routeList = routeData[this.locationId];
					this.routeInfo = routeList.find(
						(info) => info.id === parseInt(this.routeId)
					);
					// this.routeInfo = trafficConfig.getRouteById(locationId, routeId);
					this.getOrderList();
					this.getThePriceOfTheLine();
					console.log("加载线路:", this.routeInfo);
					this.loading = false;
				} catch (error) {
					console.error("获取线路详情失败:", error);
					uni.showToast({
						title: "加载失败，请重试",
						icon: "none",
					});
					this.loading = false;
				}
			},

			// 获取线路价格
			getThePriceOfTheLine() {
				if (!this.routeInfo || !this.routeInfo.productId) {
					console.error("没有找到产品ID");
					return;
				}

				this.loading = true;

				getGoodsDetail({
						Id: this.routeInfo.productId,
						// Id:'140,141'
					})
					.then((res) => {
						if (res && res.Data) {
							const data = res.Data;
							console.log("商品列表 data=>", data);
							this.products = res.Data;
							// 获取价格列表
							if (data.ProductSpecList && data.ProductSpecList.length > 0) {
								this.priceList = data.ProductSpecList.map((item) => {
									let name = '标准票';
									let specName = '';
									// 兼容中英文括号
									if (item.SpecName) {
										let match = item.SpecName.match(/^(.*?)[（(](.*)[）)]$/);
										if (match) {
											name = match[1];
											specName = match[2];
										} else {
											name = item.SpecName;
											specName = '';
										}
									}
									return {
										id: item.Id,
										Name: item.Name,
										name,
										specName,
										price: item.Price,
										productSpecId: item.Id,
										description: item.Description || "",
										shopId: item.shopId || "",
										merchantID: item.merchantID || "",
										...item,
									};
								});

								// 设置默认选中第一个价格
								if (this.priceList.length > 0) {
									this.selectType(0);
								}
								console.log("priceList =>", this.priceList);
							} else {
								// 如果没有规格价格，使用默认价格
								this.priceList = [{
									id: "",
									Name: '标准票',
									name: "标准票",
									specName: "",
									price: this.routeInfo.ticketPrice || 10,
									description: "",
								}, ];
								this.selectType(0);
							}
						}

						this.loading = false;
					})
					.catch((err) => {
						console.error("获取价格失败:", err);
						// 使用默认价格
						this.priceList = [{
							id: "",
							Name: '标准票',
							name: "标准票",
							specName: "",
							price: this.routeInfo.ticketPrice || 10,
							description: "",
						}, ];
						this.selectType(0);
						this.loading = false;
					});
			},
			// 提交订单
			async submitOrder() {
				// if (!this.checked) {
				// 	uni.showToast({
				// 		icon: "none",
				// 		title: "请先勾选协议",
				// 	});
				// 	return;
				// }
				if (this.btnLoading) {
					uni.showToast({
						icon: 'none',
						title: this.$t('traffic.buyTickets.submittingToast')
					});
					return;
				}
				// 验证表单数据
				if (this.selectedTypeIndex === -1) {
					uni.showToast({
						icon: "none",
						title: "请选择票价",
					});
					return;
				}

				// 设置加载状态
				this.btnLoading = true;

				try {
					const priceInfo = this.priceList[this.selectedTypeIndex];
					// 构建订单参数
					const orderParams = {
						BusinessId: this.products.BusinessId,
						ProductId: this.products.Id,
						ProductSpecId: priceInfo.productSpecId,
						ProductName: `${this.routeInfo.name}-${priceInfo.Name}`,
						ProductType: this.products.Type,
						Price: priceInfo.price,
						Count: this.form.quantity,
						PayStatus: 0,
						Point: 0,
						Deposit: 0,
						ContactMobile: this.passengers[0]?.phone || '',
						ContactName: this.passengers[0]?.name || '',
						CouponDiscount: this.couponTotalDiscount,
						OriginalPrice: priceInfo.price,
						PlatformType: 20, // 小程序
						SettleType: 1,
						payType: 0,
						IsTicket: 1, // 电子票
						ShopId: this.products.shopId || 0,
						MerchantId: this.products.MerchantID || 0,
						Persons: this.passengers.map(passenger => ({
							name: passenger.name,
							phone: passenger.phone,
							idCard: passenger.idCard
						})) || []
					};

					console.log(orderParams);

					// 构建请求参数
					const requestParams = {
						OrderProductList: [orderParams],
						Coupons: this.buildCouponParams()
					};

					// 调用API提交订单
					const {
						Data
					} = await addEleCouponOrders(requestParams);
					console.log(Data);
					if (Data.IsPay === 1) {
						uni.redirectTo({
							url: `/mall_subpages/goods/payment?id=${Data.OrdersOnLineId}&delta=1`,
						});
						let order_qrcode = {
							orderId: Data.OrdersOnLineId,
							locationId: this.locationId,
							routeId: this.routeId,
						};
						uni.setStorageSync("order_qrcode", order_qrcode);
					} else {
						uni.showToast({
							icon: "none",
							title: "创建订单失败",
						});
					}
				} catch (error) {
					console.error("提交订单失败:", error);
					uni.showToast({
						icon: "none",
						title: "网络异常，请稍后再试",
					});
				} finally {
					this.btnLoading = false;
				}
			},
			selectType(index) {
				if (index >= 0 && index < this.priceList.length) {
					this.selectedTypeIndex = index;
					const selectedPrice = this.priceList[index];
					this.form.specId = selectedPrice.id;
					this.form.price = selectedPrice.price;
				}
			},
			changeQty(val) {
				if (this.form.quantity + val < 1) return;
				this.form.quantity += val;
			},

			viewMap() {
				uni.openEmbeddedMiniProgram({
					appId: "wx76a6823f3bb55d2b",
				});
			},

			// 上一张车票
			async prevTicket() {
				if (this.codeIndex > 0) {
					this.codeIndex--;
				} else {
					this.codeIndex = this.ticketList.length - 1; // 切换到最后一张
				}
				this.ticketData = this.ticketList[this.codeIndex];
				await this.getOrderData()
				this.showQrcode(); // 刷新二维码
			},

			// 下一张车票
			async nextTicket() {
				if (this.codeIndex < this.ticketList.length - 1) {
					this.codeIndex++;
				} else {
					this.codeIndex = 0; // 切换到第一张
				}
				this.ticketData = this.ticketList[this.codeIndex];
				await this.getOrderData()
				this.showQrcode(); // 刷新二维码
			},
		},
	};
</script>


<style lang="less" scoped>
	.buyBox {
		padding-bottom: 330rpx;
	}

	/* 乘客信息卡片 */
	.passenger-info-card {
		margin-top: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		position: relative;
		z-index: 2;

		.info-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.info-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;

				.passenger-count-tip {
					font-size: 24rpx;
					color: #999;
					font-weight: normal;
					margin-left: 10rpx;
				}
			}

			.add-passenger-btn {
				display: flex;
				align-items: center;
				background-color: #f8f8f8;
				padding: 6rpx 16rpx;
				border-radius: 30rpx;

				.add-icon {
					font-size: 28rpx;
					color: #3a7fe6;
					margin-right: 6rpx;
				}

				.add-text {
					color: #3a7fe6;
					font-size: 24rpx;
				}
			}
		}

		.passenger-list {
			.passenger-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;

				&:last-child {
					border-bottom: none;
				}

				.passenger-index {
					font-size: 28rpx;
					color: #666;
					margin-right: 20rpx;
					min-width: 80rpx;
				}

				.passenger-details {
					flex: 1;

					.passenger-name {
						font-size: 28rpx;
						color: #333;
					}

					.id-number {
						font-size: 28rpx;
						color: #666;
						margin-left: 10rpx;
					}

					.id-full {
						display: block;
						font-size: 24rpx;
						color: #999;
						margin-top: 6rpx;
					}
				}

				.delete-btn {
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.delete-icon {
						font-size: 36rpx;
						color: #ccc;
					}
				}
			}

			.no-passenger {
				padding: 40rpx 0;
				text-align: center;

				.no-passenger-tip {
					font-size: 28rpx;
					color: #999;
				}
			}
		}
	}


	/* 弹窗样式 */
	.popup-content {
		background-color: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		overflow: hidden;
		max-height: 80vh;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #eee;

			.popup-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}

			.popup-close {
				font-size: 40rpx;
				color: #999;
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.popup-body {
			max-height: calc(80vh - 100rpx);
			overflow-y: auto;
		}
	}

	/* 优惠券区域 */
	.coupon-area {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		position: relative;
		z-index: 2;
		.coupon-section {
			.coupon-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.section-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-right: 20rpx;
				}

				.coupon-status {
					flex: 1;
					font-size: 24rpx;
					color: #3a7fe6;

					&.available {
						color: #3a7fe6;
					}

					&.unavailable {
						color: #999;
					}
				}
			}

			.coupon-selection {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;
				padding: 0 20rpx;
				background-color: #f5f5f5;
				border-radius: 8rpx;

				.select-text {
					font-size: 28rpx;
					color: #666;
				}

				.arrow-icon {
					width: 24rpx;
					height: 24rpx;
				}
			}
		}
	}


	.mpBuyTickets {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f8fa;
		box-sizing: border-box;
		padding: 30rpx;
		position: relative;
		// background-color: #EFF7FF;
		background-color: #b6e8fe;

		.tab {
			display: flex;
			justify-content: center;
			width: 100%;
			padding: 20rpx 0 40rpx 0;
			box-sizing: border-box;
			position: relative;
			z-index: 2;

			.tabItem {
				background-color: #fff;
				border: 2rpx solid #fff;
				width: 130rpx;
				height: 56rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				text-align: center;
				margin-right: 30rpx;
				border-radius: 50rpx;
				font-size: 26rpx;

				&.active {
					border-color: #9fddf8;
					color: #00aaff;
					background-color: #e5f7fe;
				}
			}
		}

		.refundInstructions {
			padding: 30rpx 30rpx;
			text-align: right;
			height: 100rpx;
			width: 100%;
			color: #939393;
			font-size: 24rpx;
		}

		.tabBox {
			background-color: #fff;
			border-radius: 10rpx;
			width: 100%;
			box-sizing: border-box;
			padding: 30rpx 30rpx 0 30rpx;
			position: relative;
			z-index: 2;

			.roadName {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-top: 10rpx;

				.name {
					font-weight: bold;
					font-size: 38rpx;
				}

				.viewMap {
					color: #3aa6e9;
					font-size: 26rpx;
				}
			}

			.routeSummary {
				color: #999;
				font-size: 26rpx;
				padding: 20rpx 0;
				box-sizing: border-box;
			}

			.ticketSection {
				border-top: 2rpx solid #f0f0f0;
				margin-top: 20rpx;

				.ticketTitle {
					padding: 20rpx 0;
					font-size: 38rpx;
					display: flex;
					align-items: center;

					.ticketTime {
						color: #bbb;
						font-size: 24rpx;
						padding-left: 10rpx;
						white-space: normal;
						word-break: break-all;
						width: 85%;
					}
				}

				.ticketTypes {

					padding: 10rpx 0 50rpx 0;
					box-sizing: border-box;

					.ticketType {
						border: 2rpx solid #DCDCDC;
						border-radius: 12rpx;
						padding: 30rpx;
						margin-bottom: 20rpx;
						font-size: 24rpx;
						background: #fafbfc;
						color: #333;
						cursor: pointer;
						box-sizing: border-box;
						width: 100%;
						position: relative;
						display: flex;
						align-items: flex-end;

						.ticketTypeLeft {
							width: 70%;

							.ticketName {
								font-size: 32rpx;
							}

							.ticketSpecName {
								padding-top: 10rpx;
								font-size: 24rpx;
								color: #666666;
							}
						}

						.ticketTypeRight {
							width: 30%;
							text-align: right;

							.ticketPrice {
								font-size: 40rpx;
								font-weight: 600;
							}
						}

						.tIcon {
							position: absolute;
							bottom: 0;
							right: 0;
							width: 30rpx;
						}

						&.active {
							border-color: #3aa6e9;
							// color: #3aa6e9;
							background: #e5f7fe;
						}
					}
				}

				.quantityBox {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 28rpx;
					border-top: 2rpx solid #f0f0f0;
					padding: 25rpx 0;

					.quantityBtnList {
						width: 50%;
						display: flex;
						justify-content: flex-end;
						align-items: center;

						.qtyBtn {
							width: 60rpx;
							height: 60rpx;
							border-radius: 50%;
							background: #f0f0f0;
							border: none;
							margin: 0 20rpx;
							font-size: 32rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							font-weight: 600;
						}

						.qtyNum {
							width: 40rpx;
							text-align: center;
						}
					}
				}
			}
		}

		.footerBar {
			position: fixed;
			left: 0;
			bottom: 0;
			background: #fff;
			width: 100%;
			padding: 0 30rpx 20rpx 30rpx;
			box-shadow: 0 -2rpx 10rpx #eee;

			.agreement {
				width: 100%;
				display: flex;
				align-items: center;

				.agreementIcon {
					margin-right: 10rpx;
					width: 10%;
				}

				.agreementText {
					display: flex;
					flex-wrap: wrap;
					width: 90%;
					font-size: 28rpx;
				}

				.blueText {
					color: #2796ff;
				}

				border-bottom: 2rpx solid #f0f0f0;
				padding: 20rpx 0;
			}

			.footerBarBox {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				padding: 20rpx 0;

				.totalPrice {
					color: #f44;
					font-size: 28rpx;

					.price {
						font-size: 45rpx;
						font-weight: 600;
					}

					.name {
						color: #333;
						padding-right: 10rpx;
					}
				}

				.buyBtn {
					background: #f44;
					color: #fff;
					border-radius: 50rpx;
					padding: 20rpx 60rpx;
					font-size: 32rpx;
					border: none;
				}
			}
		}

		.verifyBox {
			background: #fff;
			border-radius: 10rpx;
			padding: 40rpx 30rpx 120rpx 30rpx;
			margin-top: 20rpx;

			.verifyInputBox {
				display: flex;
				align-items: center;
				margin-bottom: 40rpx;

				.verifyInput {
					flex: 1;
					height: 70rpx;
					border: 2rpx solid #eee;
					border-radius: 10rpx;
					padding: 0 20rpx;
					font-size: 28rpx;
					background: #fafbfc;
					margin-right: 20rpx;
				}

				.verifyBtn {
					background: #3aa6e9;
					color: #fff;
					border-radius: 10rpx;
					font-size: 28rpx;
					padding: 0 40rpx;
					height: 70rpx;
					line-height: 70rpx;
					border: none;
				}
			}
		}

		.trafficMap {
			width: 100%;
			position: relative;

			.trafficMapBG {
				width: 100%;
				border-radius: 20rpx;
			}

			.trafficMapBox {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				box-sizing: border-box;
				padding: 0 30rpx;

				.addressIcon {
					width: 50rpx;
				}
			}
		}

		.noData {
			width: 100%;
			height: 300rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #999;
			position: relative;
			z-index: 2;
			background-color: #fff;
			border-radius: 20rpx;
			margin-bottom: 30rpx;
			margin-top: 60rpx;
		}

		.checkTicketBox {
			width: 100%;
			min-height: 600rpx;
			// background: #f7f8fa;
			position: relative;
			z-index: 2;
			margin-bottom: 30rpx;
			// padding: 30rpx 0 0 0;
			margin-top: 60rpx;
			.ticketCard {
				width: 100%;
				margin: 0 auto;
				// background: #fff;
				// border-radius: 20rpx;
				// box-shadow: 0 4rpx 24rpx #f0f1f3;
				// padding: 0 0 80rpx 0;
				position: relative;
				overflow: visible;

				.ticketHeader {
					background-color: #fff;
					border-top-left-radius: 20rpx;
					border-top-right-radius: 20rpx;
					overflow: hidden;

					.noticeBar {
						width: 100%;
						margin: 0 auto 20rpx auto;
						background: #fff7e7;
						color: #ff883b;
						font-size: 26rpx;
						// border-radius: 12rpx;
						padding: 30rpx 30rpx;
						// text-align: center;
						letter-spacing: 1rpx;
						position: relative;
						z-index: 2;
					}

					.ticketHeaderBox {
						padding: 30rpx 30rpx 20rpx 30rpx;
						display: flex;
						justify-content: space-between;
						align-items: flex-start;

						.ticketInfo {
							flex: 1;

							.ticketTitle {
								font-size: 36rpx;
								font-weight: bold;
								color: #222;
								display: flex;
								align-items: center;

								.ticketStatus {
									font-size: 24rpx;
									color: #ff8888;
									background: #fff2f0;
									border-radius: 8rpx;
									padding: 4rpx 14rpx;
									margin-left: 12rpx;
									font-weight: normal;
								}
							}

							.ticketDetail {
								font-size: 28rpx;
								color: #222;
								padding-top: 20rpx;
							}
						}
					}
				}

				.dashedLineWrap {
					position: relative;
					width: 100%;
					height: 40rpx;
					margin: 32rpx 0 0 0;
					display: flex;
					align-items: center;
					justify-content: center;

					.halfCircle {
						position: absolute;
						top: 50%;
						width: 40rpx;
						height: 40rpx;
						background: #f7f8fa;
						border-radius: 50%;
						z-index: 2;
						transform: translateY(-50%);

						&.left {
							left: -20rpx;
						}

						&.right {
							right: -20rpx;
						}
					}

					.dashedLine {
						width: 92%;
						margin: 0 auto;
						border-bottom: 2rpx dashed #999;
						height: 0;
						z-index: 1;
					}
				}

				.lineBox {
					width: 100%;

					// background-color: pink;
				}

				.lineImg {
					width: 100%;
					// height: 60rpx;
					display: block;
				}

				.qrSection {
					display: flex;
					flex-direction: column;
					align-items: center;
					// margin-top: 24rpx;
					position: relative;
					background-color: #fff;
					padding: 30rpx 0 50rpx 0;
					border-bottom-left-radius: 20rpx;
					border-bottom-right-radius: 20rpx;

					.qrTips {
						color: #27282e;
						font-size: 28rpx;
					}

					.qrImg {
						position: relative;
						z-index: 1;

						.canvas-container {
							position: relative;
							width: 170px;
							height: 170px;
						}

						.noQRCode {
							width: 170px;
							height: 170px;
							position: relative;

							.qrcodeImg {
								width: 100%;
							}

							.maskBox {
								position: absolute;
								z-index: 999;
								top: 0;
								left: 0;
								right: 0;
								bottom: 0;
								background-color: rgba(45, 45, 45, 0.95);
								width: 100%;
								height: 100%;
								display: flex;
								justify-content: center;
								align-items: center;
								border-radius: 8rpx;

								.maskText {
									color: #333;
									// font-size: 28rpx;
									background-color: #fff;
									padding: 10rpx 30rpx;
									border-radius: 30rpx;
								}
							}
						}
					}

					.qrTip {
						color: #333;
						font-size: 26rpx;
						padding-top: 10rpx;
					}

					.qrTypeList {
						padding: 20rpx;

						.qrType {
							padding: 0;

							&:first-of-type {
								padding-bottom: 10rpx;
							}
						}
					}

					.qrType {
						color: #ff6b0d;
						font-size: 34rpx;
						font-weight: bold;
						padding: 20rpx;
						text-align: center;
					}
				}

				.useBtn {
					width: 90%;
					margin: 80rpx auto 30rpx auto;
					background: #fff7e8;
					color: #333;
					border-radius: 50rpx;
					font-size: 32rpx;
					padding: 18rpx 0;
					border: 2rpx solid #ff6b0d;
					display: block;
					font-weight: bold;
					letter-spacing: 2rpx;
					opacity: 1;
					text-align: center;
				}
			}
		}
	}

	.idCards {
		padding-top: 20rpx;
		font-size: 28rpx;

		.num {
			font-weight: 600;
			font-size: 36rpx;
			color: #ff6b0d;
		}
	}

	.ticketDate {
		width: 100%;
		display: flex;
		justify-content: space-between;

		.ticketDateBox {
			width: 50%;
			font-size: 26rpx;
			// color: #fa5641;
			padding-top: 20rpx;
			display: flex;
			align-items: center;
			// padding: 30rpx;
			// font-weight: 600;

			.label {
				margin-right: 20rpx;
			}

			.date {
				width: 50%;
				color: #ff6b0d;
				font-size: 30rpx;
				font-weight: 600;
			}
		}

		.ticketCountCircle {
			width: 50%;
			display: flex;
			align-items: flex-end;
			justify-content: flex-end;
			font-size: 28rpx;
			color: #b3b6bb;
			letter-spacing: 2rpx;

			.price {
				font-weight: 600;
				font-size: 42rpx;
				color: #fa4830;
			}

			.countBox {
				// background: #feecea;
				color: #ff6b0d;
				padding: 0 6rpx;
				margin-left: 4rpx;
				font-size: 42rpx;

				.unit {
					color: #b3b6bb;
					font-size: 28rpx;
				}
			}
		}
	}

	.gifImg {
		width: 100vw;
		// height: 40vh;
		position: absolute;
		top: 0;
		left: 0;
	}

	.descBox {
		height: 50vh;
		width: 100%;
		padding: 30rpx;

		.title {
			text-align: center;
			padding-bottom: 30rpx;
		}
	}

	.numBox {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 24rpx;

		.spot {
			display: flex;
			justify-content: center;
			margin-bottom: 20rpx;
			padding-top: 20rpx;

			.spotItem {
				width: 16rpx;
				height: 16rpx;
				background-color: #d8d8d8;
				border-radius: 50%;
				margin: 0 5rpx;

				&.active {
					background-color: #00aaff; // Active spot color
				}
			}
		}

		.changeBtn {
			display: flex;
			justify-content: space-around;
			width: 50%; // Adjust as needed

			.leftBtn,
			.rightBtn {
				width: 300rpx; // Adjust as needed
				height: 300rpx; // Adjust as needed
				padding: 20rpx 40rpx;
			}
		}
	}

	.qrTip {
		color: #333;
		font-size: 26rpx;
		padding-top: 10rpx;
	}

	.ticketTime {
		word-break: break-all;
		white-space: normal;
	}
</style>